import Vue from 'vue'
import VueRouter from 'vue-router'
import hasBottomNav from '../views/hasBottomNav'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'hasBottomNav',
    component: hasBottomNav,
    redirect: '/home',
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import ('../views/Home')
      },
      {
        path: 'types',
        name: 'types',
        component: () => import ('../views/types')
      },
      {
        path: 'cart',
        name: 'cart',
        meta: {
          isRequire: true
        },
        component: () => import ('../views/cart')
      },
      {
        path: 'user',
        name: 'user',
        component: () => import ('../views/user')
      }
    ]
  },{
    path: '/detail',
    name: 'Detail',
    component: () => import ('../views/Detail')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import ('../views/login')
  },
  {
    path: '/search',
    name: 'search',
    component: () => import ('../views/search')
  }
]
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  if(typeof(location)=="string"){
    var Separator = "&";
    if(location.indexOf('?')==-1) { Separator='?'; }
    location = location + Separator + "random=" + Math.random();
  }
  return routerPush.call(this, location).catch(error=> error)
}
 

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if(to.matched.some(item => item.meta.isRequire)) {
    var token = localStorage.getItem('token')
    if(!token) {
      if(to.name === 'login') {
        next()
      } else {
        next('/login')
      }
    } else {
      next()
    }
  } else {
    next()
  }
})
export default router
